<?php

namespace App\Api\Three\Distribution;

use App\Api\ChannelApi;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;

// use function GuzzleHttp\json_decode;

class HuLianWangFenXiao extends ChannelApi
{
    protected $appKey = '';
    protected $url = '';
    protected $secret = '';
    protected $channel = '';
    protected $HTTPOK = 1; //检查接口返回的数据 返回1 代表返回正确
    protected $log;
    protected $accessToken; //token
    protected $accesstokenUrl; //获取accesstoken url地址
    protected $app_id; //appid
    protected $app_key; //appid
    protected $grant_type;
    protected $sourceId;
    protected $key = '6f3bb3f12001ab5bcefc9d91014b8f8a';
    public function __construct($url = '', $data = '')
    {
        $data = strToKeyValArr($data);
        // 南沙
        $this->pname = 'HuLianWangFengXiao';
        $this->log = new Logger('HuLianWangFengXiao');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/HuLianWangFengXiao.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->url = $url;
        //accesstoken 请求地址
        $this->accesstokenUrl = '111.7.112.55:20110/oppf';
        //系统标识 channel_HN7EM0
        $this->app_id = $data['app_id'];
        $this->app_key = $data['app_key'];
        $this->grant_type = $data['grant_type'];
        $this->sourceId = $data['sourceId'];
    }

    //通过手机号查询用户可办理的套餐列表和活动列表
    public function queryMenu($data)
    {

        $res = $this->getAccesstoken(); //获取accessToken
        if($res['code'] != 200) {
            return $res;
        }
        $busiSerial = uniqid('HLWFX', true); //"生成唯一流水号",
        $busiCode = 'EC_UIP_FX_QUERY_MARKET';
        $timestamp = date('YmdHis');
        //获取接口请求的系统参数
        $sysdata = $this->getSysparams([
            'busiCode' => $busiCode,
            'timestamp' => $timestamp,
            'busiSerial' => $busiSerial
        ]);


        $params = [
            'sysparams' => [
                'busiCode' => $busiCode,
                'sourceId' => $this->sourceId,
                'busiSerial' => $busiSerial,
                'format' => 'json'
            ],
            'busiparams' => [
                'svcNum' => $data['mobile']
            ]
        ];
        $json = json_encode($params, JSON_UNESCAPED_UNICODE);
        $aesstr = $this->aes($json);

        $signdata = $sysdata;
        $signdata['content'] = $aesstr;
        $sysdata['sign'] = $this->sign($signdata);
        // 获取最后请求的url
        $url = $this->getRequestUrl($sysdata);
        $res = $this->sendBefare($url, $aesstr, []);
        if($res['respCode'] !='00000') {
            return $this->returnMsg(-1,'失败',$res);
        }
        return $res;
    }
    protected function getRequestUrl($data)
    {
        return $this->url . '?' . http_build_query($data);
    }
    //获取办理营销活动的短信验证码
    public function getSmsCode($data)
    {
        // EC_UIP_FX_ACTIVITY_GETCODE
        $res = $this->getAccesstoken(); //获取accessToken
        if($res['code'] != 200) {
            return $res;
        }
        $busiSerial = uniqid('HLWFX', true); //"生成唯一流水号",
        $busiCode = 'EC_UIP_FX_ACTIVITY_GETCODE';
        $timestamp = date('YmdHis');
        //获取接口请求的系统参数
        $sysdata = $this->getSysparams([
            'busiCode' => $busiCode,
            'timestamp' => $timestamp,
            'busiSerial' => $busiSerial
        ]);

        $params = [
            'sysparams' => [
                'busiCode' => $busiCode,
                'sourceId' => $this->sourceId,
                'busiSerial' => $busiSerial,
                'format' => 'json'
            ],
            'busiparams' => [
                'svcNum' => $data['mobile'],
                'offerId' => $data['offerId'],
                'mealTwoLevel' => '' //需要传入二级渠道标识的分销商传入，不是必传项
            ]
        ];
        $json = json_encode($params, JSON_UNESCAPED_UNICODE);

        $aesstr = $this->aes($json);
        $signdata = $sysdata;
        $signdata['content'] = $aesstr;

        $sysdata['sign'] = $this->sign($signdata);
        // 获取最后请求的url
        $url = $this->getRequestUrl($sysdata);
        $res = $this->sendBefare($url, $aesstr, []);
        if($res['respCode'] !='00000') {
            return $this->returnMsg(-1,'失败',$res);
        }
        return $res;

    }


    protected function getSysparams($data)
    {
        return [
            'method' => $data['busiCode'],
            'format' => 'json',
            'appId' => $this->app_id,
            'version' => '1.0',
            'busiSerial' => $data['busiSerial'],
            'accessToken' => $this->accessToken,
            'timestamp' => $data['timestamp'],
        ];
    }

    public function aes($originalData)
    {
        $bkey = hex2bin($this->key);
        $a = openssl_encrypt($originalData, 'AES-128-ECB', $bkey, OPENSSL_RAW_DATA);
        $c = bin2hex($a);
        $b = strtoupper($c);
        return $b;
    }
    public function post($url, $json)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_URL, $url);
        $jstr = curl_exec($ch);
        curl_close($ch);
        if (empty($jstr)) {
            throw new Exception('无响应数据');
        }
        return $jstr;
    }
    public function sign($params)
    {
        $this->key = '6f3bb3f12001ab5bcefc9d91014b8f8a';
        ksort($params);
        $arr = array_filter($params);
        foreach ($arr as $k => $v) {
            $a[] = $k . $v;
        }
        $b = $this->key . implode('', $a) . $this->key;
        $m = hash_hmac('sha256', $b, $this->key, true);
        return bin2hex($m);
    }

    protected function getAccesstoken()
    {
        $url = $this->accesstokenUrl . '?' . http_build_query(['app_id' => $this->app_id, 'app_key' => $this->app_key, 'grant_type' => $this->grant_type]);
        $res = $this->sendBefare($url, [], []);
        if (array_key_exists('access_token', $res)) {
            $this->accessToken = $res['access_token'];
            return $this->returnMsg(200, '成功');
        }
        return $this->returnMsg(-1, '验证token失败，请联系管理员');
    }

    public function sendBefare($url, $data, $headers, $isPost = 1)
    {

        $curl = curl_init(); // 启动一个CURL会话

        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if ($isPost == 1) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        if (curl_error($curl)) {
            $res = curl_error($curl);
            var_dump($res);
            return $res;
        }
        curl_close($curl); // 关闭CURL会话
        return json_decode($result,true);
    }

}